package com.mycat.mq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 发布/订阅中的发布者（publish/subscribe）
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2017-01-04
 */
public class TopicPublish {

    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    //发送的消息数量
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        //连接工厂
        TopicConnectionFactory topicConnectionFactory;
        //连接
        TopicConnection topicConnection = null;
        //会话 接受或者发送消息的线程
        TopicSession topicSession;
        //消息的目的地
        Topic topic;
        //消息生产者
        TopicPublisher topicPublisher;
        //实例化连接工厂
        topicConnectionFactory = new ActiveMQConnectionFactory(TopicPublish.USERNAME, TopicPublish.PASSWORD, TopicPublish.BROKEURL);
        try {
            //通过连接工厂获取连接
            topicConnection = topicConnectionFactory.createTopicConnection();
            //启动连接
            topicConnection.start();
            //创建session
            topicSession = topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
            //创建一个名称为HelloWorld的消息队列
            topic = topicSession.createTopic("TestPUB_SUB");
            //创建消息生产者
            topicPublisher = topicSession.createPublisher(topic);
            //发送消息
            sendMessage(topicSession, topicPublisher);

            topicSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (topicConnection != null) {
                try {
                    topicConnection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 发送消息
     *
     * @param topicSession
     * @param topicPublisher 消息生产者
     * @throws Exception
     */
    public static void sendMessage(TopicSession topicSession, TopicPublisher topicPublisher) throws Exception {
        for (int i = 1; i <= TopicPublish.SENDNUM; i++) {
            //创建一条文本消息
            TextMessage message = topicSession.createTextMessage("ActiveMQ 发送消息" + i);
            System.out.println("发送消息：Activemq 发送消息" + i + "---------" + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss.SSS").format(new Date()));
            //通过消息生产者发出消息
            topicPublisher.send(message);
        }

    }
}
